package com.cjy.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.cjy.dao.FasdfsFileRepository;
import com.cjy.dao.ImageTypeRepository;
import com.cjy.pojo.FasdfsFile;
import com.cjy.pojo.SystemResult;
import com.cjy.pojo.User;
import com.cjy.service.FastdfsService;
import com.cjy.util.FastDFSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class FastdfsServiceImpl implements FastdfsService {

    @Autowired
    private FasdfsFileRepository fasdfsFileRepository;

    @Autowired
    private ImageTypeRepository imageTypeRepository;

    @Autowired
    private HttpSession session;

    @Value("${fastdfs_domaint}")
    private String fastdfsDomaint;

    @Override
    public SystemResult uploadFile(MultipartFile file, String imageTypeId, String isPrivate) {
        if (file.isEmpty()) {
            return SystemResult.err("文件不能为空");
        }
        if (file.getSize() > 1024*1024*5) {
            return SystemResult.err("文件不能超过5MB");
        }
        try {
            String[] result = FastDFSClient.uploadFile(file.getInputStream(), file.getOriginalFilename());
            FasdfsFile fasDFSList = new FasdfsFile();
            fasDFSList.setId(null);
            fasDFSList.setFileName(file.getOriginalFilename());
            String fileNameFDFS = FastDFSClient.getFileNameFDFS(result[1]);
            fasDFSList.setFileNameDfs(fileNameFDFS);
            fasDFSList.setCreateTime(new Date());
            fasDFSList.setGroupName(result[0]);
            fasDFSList.setFileSize(file.getSize());
            fasDFSList.setRemoteName(result[1]);
            fasDFSList.setImageType(imageTypeRepository.getOne(Long.parseLong(imageTypeId)));
            fasDFSList.setPrivate("0".equals(isPrivate) ? false : true);
            User user = (User) session.getAttribute("user");
            fasDFSList.setUserId(user.getId());
            FasdfsFile save = fasdfsFileRepository.save(fasDFSList);
            if (save != null){
                return SystemResult.ok(fileNameFDFS);
            }
            return SystemResult.err("文件上传失败");
        } catch (Exception e) {
            e.printStackTrace();
            return SystemResult.err("文件上传失败");
        }
    }

    @Override
    public SystemResult uploadFile2(MultipartFile file, String imageTypeId, String isPrivate) {
        if (file.isEmpty()) {
            return SystemResult.err("文件不能为空");
        }
        if (file.getSize() > 1024*1024*5) {
            return SystemResult.err("文件不能超过5MB");
        }
        try {
            String[] result = FastDFSClient.uploadFile(file.getInputStream(), file.getOriginalFilename());
            FasdfsFile fasDFSList = new FasdfsFile();
            fasDFSList.setId(null);
            fasDFSList.setFileName(file.getOriginalFilename());
            String fileNameFDFS = FastDFSClient.getFileNameFDFS(result[1]);
            fasDFSList.setFileNameDfs(fileNameFDFS);
            fasDFSList.setCreateTime(new Date());
            fasDFSList.setGroupName(result[0]);
            fasDFSList.setFileSize(file.getSize());
            fasDFSList.setRemoteName(result[1]);
            fasDFSList.setImageType(imageTypeRepository.getOne(Long.parseLong(imageTypeId)));
            fasDFSList.setPrivate("0".equals(isPrivate) ? false : true);
            User user = (User) session.getAttribute("user");
            fasDFSList.setUserId(user.getId());
            FasdfsFile save = fasdfsFileRepository.save(fasDFSList);
            HashMap<String, Object> map = new HashMap<>();
            map.put("fileName",fileNameFDFS);
            map.put("realPath",fastdfsDomaint + fileNameFDFS);
            if (save != null){
                return SystemResult.ok(map);
            }
            return SystemResult.err("文件上传失败");
        } catch (Exception e) {
            e.printStackTrace();
            return SystemResult.err("文件上传失败");
        }
    }

    @Override
    public Page<FasdfsFile> getFastDFSByImageType(Long imageTypeId, Pageable pageable) {
        return fasdfsFileRepository.findAll(new Specification<FasdfsFile>() {
            @Override
            public Predicate toPredicate(Root<FasdfsFile> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if ( !ObjectUtil.isEmpty(imageTypeId)) {
                    predicates.add(cb.equal(root.<Boolean>get("imageType").get("id"), imageTypeId));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        }, pageable);
    }

    @Override
    @Transactional
    public SystemResult deleteImage(Long id) {
        try {
            fasdfsFileRepository.deleteById(id);
        }catch (Exception e) {
            e.printStackTrace();
            return SystemResult.err("删除文件失败");
        }
        return SystemResult.ok("删除文件成功");
    }

    @Override
    public List<FasdfsFile> findTop() {
        Page<FasdfsFile> top = fasdfsFileRepository.findTop(PageRequest.of(0, 20));
        return top.getContent();
    }

}
